import React from 'react';
import { createRoot } from 'react-dom/client';
import styles from './index.module.less';

interface ToastProps {
  message: string;
  duration?: number;
}

const Toast: React.FC<ToastProps> = ({ message, duration = 3000 }) => {
  return (
    <div className={styles.toast}>
      <div className={styles.content}>{message}</div>
    </div>
  );
};

let toastContainer: HTMLDivElement | null = null;

export const showToast = (message: string, duration?: number) => {
  // 清除已有toast
  if (toastContainer) {
    document.body.removeChild(toastContainer);
    toastContainer = null;
  }
  
  // 创建toast容器
  toastContainer = document.createElement('div');
  document.body.appendChild(toastContainer);
  
  // 渲染Toast组件
  const root = createRoot(toastContainer);
  root.render(<Toast message={message} duration={duration} />);
  
  // 自动关闭
  setTimeout(() => {
    if (toastContainer) {
      root.unmount();
      document.body.removeChild(toastContainer);
      toastContainer = null;
    }
  }, duration);
};

export default Toast;
